-- GoogleAchievementM
-- Created by chengb Oct/10/2015
-- Google成就模块
-- 成就的进度更新、显示均由Google的SDK负责管理

module("GoogleAchievementM", package.seeall);

-- 成就配置表
local achievementTable = {};

-- 根据规则存放成就
local listByRule = {};

-- 所有子规则
local rules = {};

-- 成就进度更新请求队列
local requestQuene = {};

-- 请求处理间隔（秒）
local CHECK_INTERVAL = 1;

-- 提醒玩家登录G+账号的时间间隔（秒）
local REMIND_CD = 43200;

-- 内部函数声明
local appendRequest;
local checkRequest;

-- 载入配置表
local _init = false;
local loadCsv = function()
    if _init then return end
    _init = true;

    achievementTable = {};

    google_achievement_CSV = get_google_achievement_CSV();
    for i = 1, #google_achievement_CSV do
        local id = google_achievement_CSV[i].id;
        achievementTable[id] = google_achievement_CSV[i];

        -- 根据规则存放
        local rule = google_achievement_CSV[i].rule;
        if listByRule[rule] == nil then
            listByRule[rule] = {};
        end
        table.insert(listByRule[rule], id);
    end

    google_achievement_CSV = {};
end

-- 初始化
function init()
    if not isFunctionOpen() then
        return;
    end

    if not _init then
        loadCsv()

        -- 载入所有的规则处理子模块
        rules = LOAD_PATH("game/logic/module/google_achievement");
    end
end

-- 查询成就信息
function query(id, path)
    local m = achievementTable[id];

    if not m or path == "" or path == nil then
        return m;
    else
        return m[path];
    end
end

-- 根据规则获取成就id
function getIdsByRule(id)
    return listByRule[id] or {};
end

-- 功能是否开放
function isFunctionOpen()
    if PUBLISH_PLATFORM ~= PUBLISH_TYPE_GOOGLE_PLAY then
        return false;
    end

    return true;
end

-- 成就是否达成
function isCompleted(id)
    -- 注：Google没有提供获取成就进度的接口，故默认未达成
    return false;
end

-- 更新成就进度
function tryComplete(id, count)
    local config = query(id);
    if not config then
        trace("GoogleAchievementM", "成就(%d)不存在。");
        return false;
    end

    if count <= 0 then
        trace("GoogleAchievementM", "成就步数(%d)非法。", count);
        return false;
    end

    -- 获取Google控制台配置的编号
    local gid = config.gid;

    local incremental = config.incremental;
    assert(incremental == 0 or incremental == 1, "配置错误：incremental字段只能填0或1");

    if isRemindConnectGoogle() then
        -- 当前尚未登录G+账号，抛出提醒事件
        remindConnectGoolge();
        return false;
    end

    -- 将请求投入到队列中
    appendRequest(gid, count, incremental);

    -- 定时检查
    if not ScheduleM.isSchemeAlive("GoogleAchievementM") then
        ScheduleM.createScheme("GoogleAchievementM", checkRequest, CHECK_INTERVAL, true);
    end

    return true;
end

-- 将请求投入到队列中
function appendRequest(gid, count, incremental)
    for i = 1, #requestQuene do
        local info = requestQuene[i];
        if info.gid == gid then
            -- 合并进度
            info.count = info.count + count;
            return;
        end
    end

    table.insert(requestQuene, {["gid"] = gid, ["count"] = count, ["incremental"] = incremental});
end

-- 监测请求
function checkRequest()
    if #requestQuene == 0 then
        ScheduleM.deleteScheme("GoogleAchievementM");
        trace("GoogleAchievementM", "所有进度更新请求处理完毕。");
        return;
    end

    -- 处理队列中的第一条请求
    local info  = requestQuene[1];
    local gid   = info.gid;
    local count = info.count;
    local incremental = info.incremental;

    trace("GoogleAchievementM", "处理进度更新请求：gid = %s, count = %d, incremental = %d",
        gid, count, incremental);

    -- 调用sdk更新google成就进度
    if GooglePlayAgent then
        GooglePlayAgent.incrementGoogleAchievement(gid, count, incremental);
    end

    table.remove(requestQuene, 1);
end

-- 是否绑定了G+账号
function hasBoundGoogleAccount()
    local bindAccounts = AccountM.getBindAccounts();
    if #bindAccounts == 0 then
        return false;
    end

    for _, bindAccount in pairs(bindAccounts) do
        if string.startWith(bindAccount, CHANNEL_GOOGLE) then
            return true;
        end
    end

    return false;
end

-- 是否提示登录G+游戏中心
function isRemindConnectGoogle()
    if get3rdAccountLoginInfo(CHANNEL_GOOGLE) then
        -- 已经登录了G+账号，无需提示
        return false;
    end

    local gamingAccount = getGaming3rdAccount() or "";
    if type(gamingAccount) ~= "string"  then
        return false;
    end

    if not string.startWith(gamingAccount, CHANNEL_GOOGLE) and not hasBoundGoogleAccount() then
        -- 游戏中的账号不是G+账号，并且未绑定G+账号（换句话说：只有绑定了G+账号，提示才是有意义的）
        return false;
    end

    local lastRemindTime = UserDefaultM.getStringForKey("LAST_REMIND_GOOGLE_TIME");
    lastRemindTime = tonumber(lastRemindTime) or 0;
    if os.time() - lastRemindTime < REMIND_CD then
        -- 最近刚提醒过，暂时不提醒
        return false;
    end

    return true;
end

-- 提示玩家登录G+
function remindConnectGoolge()
    EventMgr.fire(event.REMIND_CONNECT_GOOGLE);
    UserDefaultM.setStringForKey("LAST_REMIND_GOOGLE_TIME", tostring(os.time()));
end

-- 显示Google成就列表
function displayGoogleAchievements()
    if GooglePlayAgent then
        GooglePlayAgent.displayGoogleAchievements();
    else
        alert(getLocStr("disable_function"));
    end
end



